package com.qqtech.qquan.send.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.mall.dao.MallProductDao;
import com.qqtech.qquan.mall.dao.MallShopDao;
import com.qqtech.qquan.mall.dao.MallSupplierDao;
import com.qqtech.qquan.mall.enums.MallSupplierTypeDictEnum;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.order.dao.OrderBaseDao;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.service.OrderDeliveryService;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.send.cache.SendDeliverySysParamCache;
import com.qqtech.qquan.send.dao.SendDeliveryOrderDao;
import com.qqtech.qquan.send.dao.SendDeliveryOrderItemDao;
import com.qqtech.qquan.send.dao.SendDeliveryUserDao;
import com.qqtech.qquan.send.dao.SendDeliveryUserOrderDao;
import com.qqtech.qquan.send.enums.SendDeliveryOrderPickupStatusDictEnum;
import com.qqtech.qquan.send.enums.SendDeliveryOrderStatusDictEnum;
import com.qqtech.qquan.send.enums.SendDeliveryUserAuditStatusDictEnum;
import com.qqtech.qquan.send.enums.SendDeliveryUserStatusDictEnum;
import com.qqtech.qquan.send.model.SendDeliveryOrder;
import com.qqtech.qquan.send.model.SendDeliveryOrderItem;
import com.qqtech.qquan.send.model.SendDeliveryOrderItemQuery;
import com.qqtech.qquan.send.model.SendDeliveryOrderItemVo;
import com.qqtech.qquan.send.model.SendDeliveryOrderQuery;
import com.qqtech.qquan.send.model.SendDeliveryOrderVo;
import com.qqtech.qquan.send.model.SendDeliveryUser;
import com.qqtech.qquan.send.model.SendDeliveryUserOrder;
import com.qqtech.qquan.send.model.SendDeliveryUserQuery;

@Service
public class SendDeliveryOrderServiceImpl extends BaseServiceImpl<SendDeliveryOrder>
		implements SendDeliveryOrderService {
	public static final Logger log = LoggerFactory.getLogger(SendDeliveryOrderServiceImpl.class);

	@Resource
	private SendDeliveryOrderDao sendDeliveryOrderDao;

	@Resource
	private OrderBaseDao orderBaseDao;

	@Resource
	private OrderItemService orderItemService;

	@Resource
	private MallProductDao mallProductDao;

	@Resource
	private MallSupplierDao mallSupplierDao;

	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private SendDeliveryOrderItemDao sendDeliveryOrderItemDao;

	@Resource
	private SendDeliveryUserDao sendDeliveryUserDao;

	@Resource
	private MallShopDao mallShopDao;

	@Resource
	private SendDeliverySysParamCache sendDeliverySysParamCache;

	@Resource
	private SendDeliveryUserOrderDao sendDeliveryUserOrderDao;

	@Override
	protected BaseDao<SendDeliveryOrder> getBaseDao() {
		return sendDeliveryOrderDao;
	}

	@Override
	public Result createSendDeliveryOrder(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			log.info("createSendDeliveryOrder:订单号不能为空");
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			log.info("createSendDeliveryOrder:订单号{}不存在",orderNo);
			result.addErr("订单号不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			log.info("createSendDeliveryOrder:订单{}已取消",orderNo);
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseOrderTypeDictEnum.QSHOP.getCode() != orderBase.getOrderType()) {
			log.info("createSendDeliveryOrder:订单{}不是圈商订单",orderNo);
			result.addErr("该订单不是圈商订单");
			return result;
		}
		if (OrderBasePayTypeDictEnum.ONLINE.getCode() != orderBase.getPayType()) {
			log.info("createSendDeliveryOrder:订单{}不是在线付款",orderNo);
			result.addErr("该订单不是在线付款");
			return result;
		}
		/*if (orderBase.getIsExternal() != null && YesNoEnum.NO.getCode() != orderBase.getIsExternal()) {
			result.addErr("该订单不是本地供应商的订单");
			return result;
		}*/
		MallShop mallShop = mallShopDao.getById(orderBase.getShopId());
		Map<String, SendDeliveryOrderVo> mapSupplier = new HashMap<String, SendDeliveryOrderVo>();
		List<OrderItem> orderItemList = orderItemService.findByOrderNo(orderNo);
		if (orderItemList != null && !orderItemList.isEmpty()) {
			OrderDelivery orderDelivery = orderDeliveryService.getByOrderNo(orderNo);
			Timestamp now = TimeUtil.now();
			for (OrderItem orderItem : orderItemList) {
				// MallProduct mallProduct =
				// mallProductDao.getProductBySpecId(orderItem.getProductId());
				/*MallSupplier mallSupplier = mallSupplierDao.getById(orderItem.getSupplierId());
				if (mallSupplier != null
						&& mallSupplier.getType().intValue() == MallSupplierTypeDictEnum.EXTERNAL.getCode()) {
					continue;
				}
				if (mallSupplier != null
						&& mallSupplier.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode()) {
					key = mallSupplier.getId().toString();
				}*/
				String key = mallShop.getId().toString();
				SendDeliveryOrderVo sendDeliveryOrder = null;
				if (mapSupplier.containsKey(key)) {
					sendDeliveryOrder = mapSupplier.get(key);
				} else {
					sendDeliveryOrder = new SendDeliveryOrderVo();
					sendDeliveryOrder.setOrderNo(orderNo);
					sendDeliveryOrder.setSupplierId(mallShop.getId());
					sendDeliveryOrder.setQuantityTotal(0);
					sendDeliveryOrder.setNewAt(now);
					/*if (key.equals("_")) {
						sendDeliveryOrder.setSupplierAddress(mallShop.getAddress());
						sendDeliveryOrder.setSupplierName(mallShop.getName());
						sendDeliveryOrder.setSupplierPhone(mallShop.getPhone());
					} else {
						sendDeliveryOrder.setSupplierAddress(mallSupplier.getAddress());
						sendDeliveryOrder.setSupplierName(mallSupplier.getName());
						sendDeliveryOrder.setSupplierPhone(mallSupplier.getPhone());
					}*/
					sendDeliveryOrder.setSupplierAddress(mallShop.getAddress());
					sendDeliveryOrder.setSupplierName(mallShop.getName());
					sendDeliveryOrder.setSupplierPhone(mallShop.getPhone());
					sendDeliveryOrder.setAddress(orderDelivery.getAddress());
					sendDeliveryOrder.setConsignee(orderDelivery.getConsignee());
					sendDeliveryOrder.setPhone(orderDelivery.getPhone());
					sendDeliveryOrder.setItemList(new ArrayList<SendDeliveryOrderItemVo>());
					sendDeliveryOrder.setDeliveryStatus(SendDeliveryOrderStatusDictEnum.NOTDELIVERY.getCode());
					sendDeliveryOrder.setPickupStatus(SendDeliveryOrderPickupStatusDictEnum.NOTPICKUP.getCode());
					mapSupplier.put(key, sendDeliveryOrder);
				}
				sendDeliveryOrder.setQuantityTotal(sendDeliveryOrder.getQuantityTotal() + orderItem.getQuntity());
				SendDeliveryOrderItemVo sendDeliveryOrderItem = new SendDeliveryOrderItemVo();
				sendDeliveryOrderItem.setOrderItemId(orderItem.getId());
				sendDeliveryOrder.getItemList().add(sendDeliveryOrderItem);
			}
			Iterator<String> keyIter = mapSupplier.keySet().iterator();
			while (keyIter.hasNext()) {
				String supplierIdKey = keyIter.next();
				SendDeliveryOrderVo sendDeliveryOrder = mapSupplier.get(supplierIdKey);

				Integer deliveryId = sendDeliveryOrderDao.insert(sendDeliveryOrder);
				List<SendDeliveryOrderItem> itemList = new ArrayList<SendDeliveryOrderItem>(
						sendDeliveryOrder.getItemList().size());
				for (SendDeliveryOrderItemVo itemVo : sendDeliveryOrder.getItemList()) {
					SendDeliveryOrderItem item = new SendDeliveryOrderItem();
					item.setDeliveryId(deliveryId);
					item.setOrderItemId(itemVo.getOrderItemId());
					itemList.add(item);
				}
				sendDeliveryOrderItemDao.insertInBatch(itemList);
			}
			if (!mapSupplier.isEmpty()) {
				// 获取配送人员
				String isRandom = sendDeliverySysParamCache.get("is_random_select_send_delivery_user", "2");// 是否随机选择配送人员
																											// 2否
																											// 1是
				if (isRandom.equals(YesNoEnum.NO.getCode() + "")) { // 2
																	// 就选择顶级配送人员
					SendDeliveryUserQuery q = new SendDeliveryUserQuery();
					q.setAuditStatus(SendDeliveryUserAuditStatusDictEnum.THROUGH.getCode());
					q.setCommunityId(orderBase.getCommunityId());
					q.setParentId(0);
					q.setParentUserId(0);
					q.setStatus(SendDeliveryUserStatusDictEnum.OPEN.getCode());
					List<SendDeliveryUser> deliveryUserList = sendDeliveryUserDao.queryList(q);
					if (deliveryUserList != null && !deliveryUserList.isEmpty()) { // 有配送人员，设置人员
						// updateOrder.setSendDeliveryUserId(deliveryUserList.get(0).getUserId());
						SendDeliveryUserOrder sendDeliveryUserOrder = new SendDeliveryUserOrder();
						sendDeliveryUserOrder.setOrderNo(orderNo);
						sendDeliveryUserOrder.setAssignedAt(now);
						sendDeliveryUserOrder.setAssignedUserId(0);// 系统分配
						sendDeliveryUserOrder.setDeliveryUserId(deliveryUserList.get(0).getUserId());
						sendDeliveryUserOrderDao.insert(sendDeliveryUserOrder);
					} else {
						// 没有顶级配送人员时候
						q.setParentId(null);
						q.setParentUserId(null);
						deliveryUserList = sendDeliveryUserDao.queryList(q);
						if (deliveryUserList != null && !deliveryUserList.isEmpty()) { // 有配送人员，设置人员
							int number = new Random().nextInt(deliveryUserList.size());
							// updateOrder.setSendDeliveryUserId(deliveryUserList.get(number).getUserId());
							SendDeliveryUserOrder sendDeliveryUserOrder = new SendDeliveryUserOrder();
							sendDeliveryUserOrder.setOrderNo(orderNo);
							sendDeliveryUserOrder.setAssignedAt(now);
							sendDeliveryUserOrder.setAssignedUserId(0);// 系统分配
							sendDeliveryUserOrder.setDeliveryUserId(deliveryUserList.get(number).getUserId());
							sendDeliveryUserOrderDao.insert(sendDeliveryUserOrder);
						}
					}
				} else {
					SendDeliveryUserQuery q = new SendDeliveryUserQuery();
					q.setAuditStatus(SendDeliveryUserAuditStatusDictEnum.THROUGH.getCode());
					q.setCommunityId(orderBase.getCommunityId());
					q.setStatus(SendDeliveryUserStatusDictEnum.OPEN.getCode());
					List<SendDeliveryUser> deliveryUserList = sendDeliveryUserDao.queryList(q);
					if (deliveryUserList != null && !deliveryUserList.isEmpty()) { // 有配送人员，设置人员
						int number = new Random().nextInt(deliveryUserList.size());
						// updateOrder.setSendDeliveryUserId(deliveryUserList.get(number).getUserId());
						SendDeliveryUserOrder sendDeliveryUserOrder = new SendDeliveryUserOrder();
						sendDeliveryUserOrder.setOrderNo(orderNo);
						sendDeliveryUserOrder.setAssignedAt(now);
						sendDeliveryUserOrder.setAssignedUserId(0);// 系统分配
						sendDeliveryUserOrder.setDeliveryUserId(deliveryUserList.get(number).getUserId());
						sendDeliveryUserOrderDao.insert(sendDeliveryUserOrder);
					}
				}
			}
		}
		return result;
	}

	@Override
	public List<SendDeliveryOrderVo> findByOrderNo(String orderNo) {
		List<SendDeliveryOrderVo> list = null;
		if (orderNo == null || "".equals(orderNo)) {
			return list;
		}
		SendDeliveryOrderQuery orderQuery = new SendDeliveryOrderQuery();
		orderQuery.setOrderNo(orderNo);
		list = sendDeliveryOrderDao.queryList(orderQuery);
		if (list != null && !list.isEmpty()) {
			for (SendDeliveryOrderVo orderVo : list) {
				SendDeliveryOrderItemQuery itemQuery = new SendDeliveryOrderItemQuery();
				itemQuery.setDeliveryId(orderVo.getId());
				List<SendDeliveryOrderItemVo> itemList = sendDeliveryOrderItemDao.queryList(itemQuery);
				if (itemList != null && !itemList.isEmpty()) {
					for (SendDeliveryOrderItemVo sdoi : itemList) {
						sdoi.setOrderItemVo(orderItemService.getById(sdoi.getOrderItemId()));
					}
				}
				orderVo.setItemList(itemList);
			}
		}
		return list;
	}

	@Override
	public List<SendDeliveryOrderVo> findOnlyByOrderNo(String orderNo) {
		List<SendDeliveryOrderVo> list = null;
		if (orderNo == null || "".equals(orderNo)) {
			return list;
		}
		SendDeliveryOrderQuery orderQuery = new SendDeliveryOrderQuery();
		orderQuery.setOrderNo(orderNo);
		list = sendDeliveryOrderDao.queryList(orderQuery);
		return list;
	}

	@Override
	public Page<SendDeliveryOrderVo> queryPageListAdmin(SendDeliveryOrderQuery query, Pageable pageable) {
		return sendDeliveryOrderDao.queryPageListAdmin(query, pageable);
	}

}